<?php

namespace App\Models;

class Article extends Base
{

    protected $table = 'articles';

    protected $guarded = [];

    /**
     * 格式化列表数据
     */
    public static function formatDatas($list, $params = '')
    {
        foreach ($list as &$item) {
            $item = self::formatItem($item, $params);
        }

        return $list;
    }

    /**
     * 格式化单个数据
     */
    public static function formatItem($item, $params = '')
    {
        if (!$item) {
            return '';
        }

        $full_cover_img = '';
        if ($item['cover_img']) {
            $full_cover_img = full_file_url($item['cover_img']);
        }
        $item['full_cover_img'] = $full_cover_img;

        if (isset($params['source']) && $params['source'] == 'backend') {
            // 状态
            switch ($item['status']) {
                case 1:
                    $item['status_name'] = '显示';
                    break;
                case 2:
                    $item['status_name'] = '隐藏';
                    break;
                case 90:
                    $item['status_name'] = '删除';
                    break;
                default: break;
            }

            // 分类
            $cate_name = ArticleCate::where('id', $item['cate_id'])->pluck('name')->first();
            $item['cate_name'] = $cate_name;
        } else {
            // 时间
            $updated_at = $item['updated_at'];
            $item['updated_at'] && $item['updated_at'] = substr($updated_at, 0, 10);

            if (isset($params['method']) && $params['method'] == 'detail') {
                // 上一篇
                $prev_page = Article::where('updated_at', '<', strtotime($updated_at))->select('id', 'name')->first();
                $item['prev_page'] = $prev_page ? $prev_page->toArray() : '';
                // 下一篇
                $next_page = Article::where('updated_at', '>', strtotime($updated_at))->select('id', 'name')->first();
                $item['next_page'] = $next_page ? $next_page->toArray() : '';
            }
        }

        return $item;
    }
}
